﻿using System;
using System.Collections.Generic;
using System.Data.Entity;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Transactions;

namespace FW.Data
{
    public interface IDbContextFactory : IDisposable
    {
        DbContext GetContext();

        void TranComplete();
    }

    public class DbContextFactory : IDbContextFactory
    {
        private readonly DbContext _dbContext;
        private readonly TransactionScope _transaction;
        public DbContextFactory(bool usingTran = false)
        {
            _dbContext = new FWContext();

            if (usingTran)
                _transaction = new TransactionScope();
        }

        public DbContext GetContext()
        {
            return _dbContext;
        }
        public void TranComplete()
        {
            if (_transaction != null)
                _transaction.Complete();
        }

        public void Dispose()
        {
            _dbContext.Dispose();

            if (_transaction != null)
            {
                _transaction.Dispose();
            }
        }
    }
}
